package com.example.yt_app.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.example.yt_app.Activity.BaseActivity.SwipeBackBaseActivity;
import com.example.yt_app.AppManager;
import com.example.yt_app.R;

import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.JsonPaser;
import com.example.yt_app.Urils.SPTool;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.permissionx.guolindev.PermissionX;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import okhttp3.OkHttpClient;

/**
 *
 * @author dell
 * @date 2021/8/4
 */
@SuppressWarnings("ALL")
public class SpeekActivity  extends SwipeBackBaseActivity {

    private OkHttpClient okHttpClient;
    @BindView(R.id.detail_toolbar)
    Toolbar toolbar;
    @BindView(R.id.status_bar)
    TextView status_bar;
    @BindView(R.id.speech_btn)
    ImageButton speech_btn;
    private final mHandler mHandler = new mHandler();

    private SpeechRecognizer mIat;
    // 语音听写对象
    private RecognizerDialog mIatDialog;
    // 语音听写UI

    /** 用HashMap存储听写结果*/
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    private SharedPreferences mSharedPreferences;
    //缓存

    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    // 引擎类型
    private String language = "zh_cn";
    //识别语言
    private String resultType = "json";
    //结果内容数据格式
    public static boolean Speak = true;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_speech;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(toolbar).init();
        //隐藏状态栏
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        ImmersionBar.with(this).titleBar(R.id.detail_toolbar).keyboardEnable(true).init();
    }
    @Override
    protected void initView() {
        requestPower();
        AppManager.getInstance().addActivity(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        okHttpClient = new OkHttpClient();
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(SpeekActivity.this, mInitListener);
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(SpeekActivity.this, mInitListener);
        mSharedPreferences = getSharedPreferences("ASR",
                Activity.MODE_PRIVATE);
    }

    @Override
    protected void initData() {
        State.OTHER = false;
    }


    @Override
    protected SwipeBackLayout getSwipeBackLayout(int layoutId) {
        return null;
    }
    /**
     *  动态赋予权限
     * */
    public void requestPower() {
        PermissionX.init(this)
                .permissions(Manifest.permission.RECORD_AUDIO
                        ,Manifest.permission.ACCESS_NETWORK_STATE
                        ,Manifest.permission.ACCESS_WIFI_STATE)

                .onExplainRequestReason((scope, deniedList) -> {
                    scope.showRequestReasonDialog(deniedList,"HomeApp 需要您同意以下授权才能正常使用","同意","拒绝");
                })
                .request(((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        if (State.Start == false){
                            //Toast.makeText(this, "您同意了所有权限!", Toast.LENGTH_SHORT).show();
                            State.Start = true ;
                        }
                        //createLog4jLocal();
                    } else {
                        Toast.makeText(this, "您拒绝了以下权限:"+deniedList, Toast.LENGTH_SHORT).show();
                        //finish();
                    }
                }));

    }
    @SuppressWarnings("AliDeprecation")
    @SuppressLint("HandlerLeak")
    private class mHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    Voice_ZX(); //启动听写
                    break;
                default:break;
            }
        }
    }
    public void Voice_ZX() {
        Speak = false;
        if( null == mIat ){
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            showMessage( "创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化" );
            return;
        }
        mIatResults.clear();//清除数据
        setParam(); // 设置参数
        mIatDialog.setListener(mRecognizerDialogListener);
        //设置监听
        mIatDialog.show();// 显示对话框
    }
    //取消听写
    public  void Voice_Cancel(){
        mIat.cancel();
        System.out.println("取消听写");
    }
    // 停止听写
    public  void Voice_Stop(){
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        mIat.stopListening();
        System.out.println("停止听写");
    }
    private long downTime = 0;//Button被按下时的时间
    private long thisTime = 0;

    @Override
    protected void setListener() {
        //toolbar返回按钮监听
        toolbar.setNavigationOnClickListener(v ->finish() );
        speech_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                downTime = event.getDownTime(); //手指按下时间
                thisTime = event.getEventTime();
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN: //手指按下
                        Speak = true;
                        Thread thread = new Thread(){
                            @Override
                            public void run() {
                                while (Speak) {

                                    if (thisTime - downTime >= 400) {
                                        Message message = Message.obtain();
                                        message.what = 0;
                                        mHandler.sendMessage(message);
                                        status_bar.setText("你请说，我听着的呢！");
                                        Delay.Delay_ms(200);
                                    }
                                }
                            }
                        };
                        thread.start();

                        break;
                    /*case MotionEvent.ACTION_MOVE: //手指移动（从手指按下到抬起 move多次执行）
                        System.out.println("X:"+event.getX()+"\r\r"+"Y:"+event.getY());
                        break;*/
                    case MotionEvent.ACTION_UP: //手指抬起
                        Voice_Stop();
                        //短按事件
                        if(thisTime - downTime < 400 ){
                            status_bar.setText("时间太短啦，我没听清");
                        }
                        break;

                    default:break;
                }
                return false;
            }
        });

    }
    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d("TAG", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showMessage("初始化失败，错误码：" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
            }
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        @Override
        public void onResult(RecognizerResult results, boolean isLast) {

            printResult(results);//结果数据解析
            Voice_Stop();

        }

        /**
         * 识别回调错误.
         */
        @Override
        public void onError(SpeechError error) {
            showMessage(error.getPlainDescription(true));
        }

    };

    /**
     * 数据解析
     *
     * @param results
     */
    private void printResult(RecognizerResult results) {
        String text = JsonPaser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }

        status_bar.setText(resultBuffer.toString());//听写结果显示

    }

    /**
     * 参数设置
     *
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);
        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);

        if ("zh_cn".equals(language)) {
            String lag = mSharedPreferences.getString("iat_language_preference",
                    "mandarin");
            Log.e("TAG", "language:" + language);// 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        } else {

            mIat.setParameter(SpeechConstant.LANGUAGE, language);
        }
        Log.e("TAG", "last language:" + mIat.getParameter(SpeechConstant.LANGUAGE));

        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageState() + "/msc/iat.wav");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        State.OTHER = true;
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

}